﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Dynamic;
using Facebook;
using System.Net;
using System.IO;
using System.Xml.Linq;
using NewsMine.DomainObjects;

namespace WebApp1.AdminSection
{
    public partial class fbadmin : System.Web.UI.Page
    {
        #region Properties
        public string ApplicationId
        {
            get
            {
                return ConfigurationManager.AppSettings["ApplicationId"];
            }
        }
        public string ExtendedPermissions
        {
            get
            {
                return ConfigurationManager.AppSettings["ExtendedPermissions"];
            }
        }
        public string AppSecret
        {
            get
            {
                return ConfigurationManager.AppSettings["ApplicationSecret"];
            }
        }
        public string AccessToken { get; set; }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            DisplayExistingFBAccounts();

            if (!IsPostBack && Request["code"] != null)
            {
                isFacebookLoginRedirected = false;
                //if (!Post_Message("This is a message from aspx page"))
                CheckAuthorization(); 
            }
        }

        private void DisplayExistingFBAccounts()
        {
            object objFacebookAccounts = NewsMine.Storage.Defaults.SettingsStore.Get("fbaccounts");

            if (objFacebookAccounts == null)
            {
                Response.Write("No accounts are mapped...<br/>");
                return;
            }

            if (objFacebookAccounts.GetType() != typeof(FacebookAccount))
            {
                Response.Write("No accounts are mapped...<br/>");
                return;
            }

            FacebookAccount fbAccount = (FacebookAccount)objFacebookAccounts;

            Response.Write("<br/>Name:" + fbAccount.Name);
            Response.Write("<br/>Created date:" + fbAccount.TokenCreatedTime.AddHours(5).AddMinutes(30).ToString());
            Response.Write("<br/>expiry date:" + fbAccount.TokenExpiryTime.AddHours(5).AddMinutes(30).ToString());

            Response.Write("<br/><b>Pages info</b>");

            foreach (var item in fbAccount.PageInformation)
            {

                Response.Write("<br/>" + item.Name);
            }


        }

        bool isFacebookLoginRedirected = false;

        protected void btnAssociateNewFbAccount_Click(object sender, EventArgs e)
        {
            isFacebookLoginRedirected = true;
            Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}", ApplicationId, Request.Url.AbsoluteUri, ExtendedPermissions));
            
        }

        string picPath = @"C:\Users\surendra\Pictures\allIndiaNewspapers.jpg";

        private bool Post_Picture(string Picture_Path, string Picture_Caption, string AT, bool Is_User_Wall,string pageId)
        {
            // new FacebookClient instance (AT: user access token or page access token)
            var fb = new FacebookClient(AT);

            string AlbumID = "";
            if (!Is_User_Wall)
            {
                // Find the 'Wall Photos' Album Object_ID
                // alter this part to publish photos to a different album
                var query = string.Format("SELECT object_id,name FROM album WHERE owner = me()");
                dynamic r1 = fb.Get("fql", new { q = query });
                foreach (var post in r1.data)
                {
                    if (post.name == "Wall Photos") { AlbumID = Convert.ToString(post.object_id); }
                }

                if (AlbumID == "") { return false; }
            }

            dynamic parameters = new ExpandoObject();
            parameters.message = Picture_Caption;
            parameters.no_story = 0;
            // parameters.published = 0;

            parameters.source = new FacebookMediaObject
            {
                ContentType = "image/jpeg",
                FileName = Path.GetFileName(Picture_Path)
            }.SetValue(File.ReadAllBytes(Picture_Path));

            try
            {
                if (Is_User_Wall)
                {
                    // Post the image/picture to User wall
                    //fb.Post("me/photos", parameters);
                    fb.Post(pageId +"/photos", parameters);

                    
                    //fb.Post("me/feed", parameters);

                    //fb.Post("636622736349107/feed", parameters);

                    //fb.Post("702067566476045/photos", parameters);
                }
                else
                {
                    // Post the image/picture to the Page's Wall Photo album
                    fb.Post("/" + AlbumID + "/photos", parameters);
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }


        private void CheckAuthorization()
        {
            if (Request["code"] != null)
            {
                Dictionary<string, string> tokens = new Dictionary<string, string>();
                string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}", ApplicationId, Request.Url.AbsoluteUri, ExtendedPermissions, Request["Code"].ToString(), AppSecret);
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    string vals = reader.ReadToEnd();
                    foreach (string token in vals.Split('&'))
                    {
                        tokens.Add(token.Substring(0, token.IndexOf("=")), token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
                    }
                    this.AccessToken = tokens["access_token"];

                    var result1 = GetExtendedAccessToken(AccessToken);
                    var extendedToken = result1.access_token;
                    this.AccessToken = extendedToken;

                    NewsMine.DomainObjects.FacebookAccount fbAccount = new NewsMine.DomainObjects.FacebookAccount();

                    var fb = new FacebookClient(this.AccessToken);
                    dynamic userInfo = fb.Get("/me/");

                    fbAccount.Name = userInfo.name;
                    fbAccount.Id = userInfo.id;

                    dynamic pageResults = fb.Get("/me/accounts?type=page");
                    int pageCount = pageResults.data.Count;

                    for (int i = 0; i < pageCount; i++)
                    {
                        var fbPage = new FacebookPage { Name = pageResults.data[i].name, Id = pageResults.data[i].id, AccessToken = pageResults.data[i].access_token };

                        dynamic extendedTokenResponse = GetExtendedAccessToken(fbPage.AccessToken);
                        fbPage.AccessToken = extendedTokenResponse.access_token;

                        fbPage.TokenCreatedTime = DateTime.UtcNow;
                        fbPage.TokenExpiryTime = fbPage.TokenCreatedTime.AddSeconds(Convert.ToInt32(extendedTokenResponse.expires));

                        fbAccount.PageInformation.Add(fbPage);
                        
                        //fbAccount.PageInformation.Add(pageResults.data[i].name, pageResults.data[i].id);
                    }


                    NewsMine.Storage.Defaults.SettingsStore.Replace("fbaccounts", fbAccount);


                    //var doc1 = XDocument.Load(Server.MapPath("~/Token/AccessToken.xml"));
                    //doc1.Root.SetValue(this.AccessToken);
                    //doc1.Save(Server.MapPath("~/Token/AccessToken.xml"));
                }
            }
            else
            {

            }

        }


        #region Get long lived access token
        public dynamic GetExtendedAccessToken(string oldToken)
        {
            dynamic result = new ExpandoObject();
            try
            {
                var api = new FacebookClient
                {
                    AccessToken = oldToken,
                    AppId = ApplicationId,
                    AppSecret = AppSecret
                };
                dynamic parameters = new ExpandoObject();
                parameters.grant_type = "fb_exchange_token";
                parameters.fb_exchange_token = oldToken;
                parameters.client_id = ApplicationId;
                parameters.client_secret = AppSecret;
                result = api.Get("oauth/access_token", parameters);
            }
            catch (FacebookOAuthException err)
            {
                result.error = "Error";
                result.message = err.Message;
            }
            catch (Exception err)
            {
                result.error = "Error";
                result.message = err.Message;
            }
            return result;
        }
        #endregion
    }
}